<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in" ref="dialogBox">
      <div class="cornerComment-in-title">
        <!--        1 学生 2 职工-->
        <span>复制内部问卷</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <el-col :span="24" class="warp-main">
          <el-form ref="infoForm" :model="infoForm" :rules="rules" label-width="140px">
            <el-form-item label="问卷标题:" prop="title">
              <el-input v-model="infoForm.title" placeholder="填写投票名称"></el-input>
            </el-form-item>
            <el-form-item label="问卷描述:" prop="description">
              <quill-editor v-model="infoForm.description"
                            ref="myQuillEditor"
                            class="editer"
                            :options="editorOption" @ready="onEditorReady($event)" placeholder="问卷描述" v-if="!editId">
              </quill-editor>
              <p v-else v-html="infoForm.description?infoForm.description:'无'"></p>
            </el-form-item>
            <el-form-item label="问卷范围:">
              <el-radio-group v-model="teachertype" @change="radiochangeTab">
                <el-radio :label="0">全校职工</el-radio>
                <el-radio :label="1">特定职工</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择特定职工:" v-if="teachertype==1">
              <el-button type="primary" @click="chooseStudent" class="mb-10" size="small" plain>选择参与问卷人员</el-button>
              <el-button @click.native="groupVisible=true" size="small">选择执行群组（多选）</el-button>
              <div>
                <el-tag
                    :key="tag.id"
                    v-for="(tag,index) in dynamicTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index)"
                    class="mr-10"
                >{{ tag.realname }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="问卷开始时间:" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date"
                                placeholder="开始时间"
                                v-model="infoForm.start_time"
                                :picker-options="pickerOptions1"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="问卷结束时间:" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date"
                                placeholder="结束时间"
                                v-model="infoForm.end_time"
                                :picker-options="pickerOptions1"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="问卷内容:">
              <div class="iconlist questionlist" v-for="(item,i) in infoForm.body">
                <div class="questionTitleIndex">{{ i + 1 }}.
                  <el-input v-model="infoForm.body[i].content" placeholder="填写问卷内容"></el-input>
                  <i class="el-icon-circle-plus-outline iconadd addicon" @click="onAdd(index)"></i>
                  <i class="el-icon-error iconadd detelicon" @click="onDetel(i)"></i>
                </div>
                <div class="questionType">
                  <div>
                    用户问卷回答类型：
                    <el-radio-group v-model="infoForm.body[i].type" @change="radioChange(i)">
                      <el-radio :label="1">单选项</el-radio>
                      <el-radio :label="2">多选项</el-radio>
                      <el-radio :label="3">输入框</el-radio>
                    </el-radio-group>
                    <span class="infoline">(选项：用户选择ABCD选项；输入框：用户自行输入文字内容)</span>
                  </div>
                  <p>
                    填写类型：
                    <el-radio-group v-model="infoForm.body[i].is_must">
                      <el-radio label="1">必填</el-radio>
                      <el-radio label="0">非必填</el-radio>
                    </el-radio-group>
                  </p>
                </div>
                <!--                  1单 2 多 3输入-->
                <div class="questionline" v-if="infoForm.body[i].type==1||infoForm.body[i].type==2">
                  <div v-for="(item,indexs) in infoForm.body[i].option" class="questionline-list">
                    <p>
                      {{ qustionCheck[indexs] }}.
                      <el-input v-model="infoForm.body[i].option[indexs].text" placeholder="填写选项内容"></el-input>
                      <i class="el-icon-circle-plus-outline iconadd addicon" @click="addlinebox(i)"
                         v-if="infoForm.body[i].option.length<26"></i>
                      <i class="el-icon-error iconadd detelicon" @click="detellinebox(i,indexs)"></i>
                    </p>
                    <p>
                      是否添加输入框：
                      <el-radio-group v-model="infoForm.body[i].option[indexs].type">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="2">否</el-radio>
                      </el-radio-group>
                    </p>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click="closePOpup" size="small">取消</el-button>
        <el-button @click="onSubmit" size="small" type="primary">确认并提交</el-button>
      </div>
    </div>
    <MultipleTeacherModle :visible.sync="studentVisible" @studentFn="studentFn"
                          :dynamicTagsArray="dynamicTagsArray"></MultipleTeacherModle>
    <!--    选择群组-->
    <groupModule :visible.sync="groupVisible" @studentFn="studentFn"></groupModule>
  </div>
</template>

<script>

import {yeartime} from "@/assets/js/common";
import teacherMultiple from '@/components/dialog/teacherMultiple.vue'

import {quillEditor} from 'vue-quill-editor' // 调用编辑器
import quillConfig from '@/assets/js/quill-config.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  props: ['visible', 'detailId'], // commoent 学生点评 collection 学生采集
  components: {
    teacherMultiple,
    quillEditor
  },
  data() {
    return {
      editorOption: quillConfig,
      groupVisible: false,
      dialogVisible: false,
      qustionCheck: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      dialogTableVisible: false,
      infoForm: {
        body: [{'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]}],
        title: '',
        start_time: yeartime(new Date()),
        end_time: yeartime(new Date()),
        user_ids: 0,
        description: '' //  描述
      },
      // 表单验证
      rules: {
        title: [
          {required: true, message: '填写问卷标题', trigger: 'blur'}
        ]
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      arryList: null,
      usersName: null,
      editId: this.$route.query.editId,
      listCheck: [],
      value1: [],
      sectionList: [],
      classesList: [],
      oldClass: {}, // 未处理的班级
      oldsection: {}, // 未处理的年段
      editClass_id: [],
      editsection_id: [],
      studentVisible: false,
      teachertype: 0,
      dynamicTags: [],
      dynamicTagsArray: {},
      editBody: null
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible && this.detailId) {
        this.Inint()
      }
      if (!this.visible) {
        this.dynamicTags = []
        this.dynamicTagsArray = {}
        this.editBody = null
        this.teachertype = 0
        this.infoForm = {
          body: [{'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]}],
          title: '',
          start_time: yeartime(new Date()),
          end_time: yeartime(new Date()),
          user_ids: 0
        }
      }
    }
  },
  created() {
  },
  methods: {
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    Inint() {
      this.$fetch(this.api.questionnaire_inside_detail, {id: this.detailId}).then((response) => {
        if (response.code === 0) {
          this.infoForm.start_time = response.vo.start_time
          this.infoForm.end_time = response.vo.end_time
          this.infoForm.title = response.vo.title
          this.infoForm.description = response.vo.description //  描述
          this.listCheck = response.list
          if (response.vo.user_ids && response.vo.user_ids.length) {
            this.teachertype = 1
            this.dynamicTags = this.getJson(response.vo.user_ids)
          }
          // if(response.vo.user_ids){
          //   this.teachertype = 1
          // }else{
          //   this.teachertype = 0
          // }
          for (let item of response.list) {
            item.is_must = item.is_must.toString()
          }
          this.editBody = response.vo
          this.infoForm.body = response.list
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    onEditorReady(editor) {
    },
    onAdd(index) {
      // this.infoForm.body.push({'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]})
      this.infoForm.body.splice(index+1, 0, {'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]})
    },
    addlinebox(i) {
      this.infoForm.body[i].option.push({text: '', type: '2'})
    },
    detellinebox(i, index) {
      console.log('删除选项内容信息：', i, this.infoForm.body)
      this.infoForm.body[i].option.splice(index, 1)
      if (!this.infoForm.body[i].option.length) {
        this.addlinebox(i)
      }
    },
    onDetel(index) {
      // this.infoForm.body.splice(index, 1)
      this.infoForm.body.splice(index, 1)
      if (!this.infoForm.body.length) {
        this.infoForm.body.push({
          'content': null,
          'type': '1',
          is_must: '1',
          'option': [{text: '', type: '2', is_commitment: '0'}]
        })
      }
    },
    // 设置默认选中
    checked() {
      console.log('默认选项判断', this.applyBookBox)
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          console.log('数值', i)
          this.$refs.table.toggleRowSelection(this.arryList[i], true)
        }
      }
    },
    radioChange(e) {
      if (this.infoForm.body[e].type == 3) {
        this.infoForm.body[e].option = []
      } else {
        this.infoForm.body[e].option = [{text: '', type: '2'}]
      }
    },
    backlist() {
      this.$router.go(-1)
    },
    radiochangeTab() {
      this.infoForm.user_ids = 0
    },
    onSubmit() {
      // 提交 this.$refs.infoForm.validate，这是表单验证
      console.log('数据提交', this.infoForm, this.value1)
      if (!this.infoForm.title) {
        this.$message({
          message: '请填写问卷标题',
          type: 'error'
        })
        return
      }
      // 1单 2 多 3输入
      for (let i in this.infoForm.body) {
        if (!this.infoForm.body[i].content) {
          this.$message({
            message: '请填写问卷内容',
            type: 'error'
          })
          return
        }
        if (this.infoForm.body[i].type == 1 || this.infoForm.body[i].type == 2) {
          for (let j in this.infoForm.body[i].option) {
            if (!this.infoForm.body[i].option[j].text) {
              console.log('none')
              this.$message({
                message: '请填写问卷选项',
                type: 'error'
              })
              return
            }
          }
        }
      }
      if (this.teachertype === 1 && !this.dynamicTags.length) {
        this.$message({
          message: '请选择特定职工',
          type: 'error'
        })
        return
      }
      let data_ = {}
      let body_ = this.infoForm.body
      for (let i in body_) {
        if (body_[i].type !== 3) {
          for (let j in body_[i].option) {
            body_[i].option[j]['index'] = this.qustionCheck[j]
          }
        }
      }
      let users = []
      for (let item of this.dynamicTags) {
        users.push(item.id)
      }
      data_.title = this.infoForm.title
      data_.start_time = this.infoForm.start_time
      data_.end_time = this.infoForm.end_time
      data_.body = JSON.stringify(body_)
      data_.user_ids = users.join(',')
      data_.description = this.infoForm.description
      console.log('提交信息data_：', data_)
      this.$refs['infoForm'].validate((valid) => {
        console.log('状态：', valid)
        if (valid) {
          this.$post(this.api.questionnaire_inside_add, data_).then(res => {
            if (res.code === 0) {
              this.$message({
                message: '复制成功',
                type: 'success'
              })
              this.$emit('InitFn')
              this.closePOpup()
              this.infoForm = {
                body: [{'title': null, is_must: '1', 'type': '1', 'content': ['']}],
                title: '',
                class_id: '',
                section_id: '',
                start_time: yeartime(new Date()),
                end_time: yeartime(new Date()),
                student_id: 0
              }
              this.teachertype = 0
              this.dynamicTags = []
              this.dynamicTagsArray = {}
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    chooseStudent() {
      let list = {}
      for (let item of this.dynamicTags) {
        list[item.id] = item
      }
      this.dynamicTagsArray = this.getJson(list)
      this.studentVisible = true
    },
    handleClose(index) {
      this.dynamicTags.splice(index, 1)
    },
    studentFn(option) {
      let list = [];
      for (let i in option) {
        list.push(option[i])
      }
      this.dynamicTags = this.getJson(list)
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
  },
  mounted() {
  }
}
</script>
<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 70%;
  height: 80%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 10px 20px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.questionTitleIndex {
  display: flex;
  align-items: center;
}
</style>


